import java.awt.image.BufferedImage;
import java.io.*;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;

import gnu.io.*;

public class serial_test
{
	private static byte[] imagebin;
	private static BufferedImage image;
	private static Serial_Base mbase;
	private static int typebyte;

	public static void main( String arg[] )
	{
		 mbase = new Serial_Base();
		 boolean flg = mbase.Serial_open("COM8",9600);

		 recieveReadyMessage();

		 readBMP();
		 System.out.println(imagebin.length);
		 sendImageInfo(image.getWidth(),image.getHeight(),typebyte,imagebin.length);
		 //image = robot.createScreenCapture(new Rectangle(0, 0, Toolkit.getDefaultToolkit().getScreenSize().width,
		 //                                                     Toolkit.getDefaultToolkit().getScreenSize().height));

		 //mbase.Serial_read();
		 reciveDataMessage();
		 while(true);
		 //mbase.Serial_close();
	 }

	public static void sendImageInfo(int w, int h,int format,int size)
	{
		String sendstr = "OK SEND IMAGE\r\n(w:"+w+",h:"+h+",pix:"+format+",s:"+size+")\r\n";
		mbase.Serial_puts(sendstr);
	}

	public static void recieveReadyMessage()
	{
		String str = "";
		String check = "GET Image Info";
		while(true)
		{
			str = mbase.Serial_read();
			if(str == null)continue;
			else if(str.equals(check))break;
		}
	}

	public static void reciveDataMessage()
	{
		String str = "";
		String check = "GET Image data";
		while(true)
		{
			str = mbase.Serial_read();
			if(str == null)continue;
			else if(str.equals(check))break;
		}
		mbase.Serial_puts("OK SEND IMAGE\r\n");
		sendData();
	}

	public static void sendData()
	{
		int i = 0;
		for(i=0;i<imagebin.length/16384;i++)
		{
			System.out.println(i*16384+"+"+16384);
			mbase.Serial_write(imagebin,i*16384,16384);
		}
		System.out.println((i*16384)+"+"+(imagebin.length-i*16384));
		mbase.Serial_write(imagebin,i*16384, imagebin.length - i*16384);
		//mbase.Serial_write(imagebin);
	}

	public static void readBMP() { // BMP読み込み
		try {
			image = ImageIO.read(new File("C:/Users/muchiki0226/Desktop/test.bmp"));

			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			BufferedOutputStream os = new BufferedOutputStream(bos);
			image.flush();
			ImageIO.write(image, "png", os);
			os.flush();
			os.close();

			System.out.println(bos.toByteArray().length);
			imagebin = new byte[bos.toByteArray().length];
			imagebin = bos.toByteArray();

			switch(image.getType())
			{
			case BufferedImage.TYPE_3BYTE_BGR:
				typebyte = 3;
				break;
			case BufferedImage.TYPE_4BYTE_ABGR:
			case BufferedImage.TYPE_4BYTE_ABGR_PRE:
				typebyte = 4;
				break;
			default:
				typebyte = 0;
				break;
			}
			System.out.println(typebyte);
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}